package com.jigsawapp.movies.ui.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.jigsawapp.movies.R;
import com.jigsawapp.movies.adapter.MovieAdapter;
import com.jigsawapp.movies.api.MoviesApi;
import com.jigsawapp.movies.bean.Movies;
import com.jigsawapp.movies.common.UIHelper;
import com.jigsawapp.movies.util.JsonUtils;
import com.kymjs.rxvolley.client.HttpCallback;

import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by jigsaw on 2016/4/23.
 * Email: fadeblack307@163.com
 */
public class MoviesFragment extends Fragment {
    @InjectView(R.id.list_view)
    ListView listView;

//    @Nullable
//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.activity_index, container, false);
//        ButterKnife.inject(this, view);
//        Log.i("kk", "create view");
//        return view;
//    }



    //这是一个办法防止viewpager滑动后 每次都会运行oncreateview 这样导致 覆盖之前的listview 导致空白页
    private View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.activity_index, container, false);

        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.inject(this, rootView);
//        Log.i("kk", "create view");
        return rootView;
    }

    public void getMovies(String pagenum, String pagesize) {
        MoviesApi.moviesIndex(pagenum, pagesize, new HttpCallback() {
            @Override
            public void onSuccess(Map<String, String> headers, byte[] t) {
                super.onSuccess(headers, t);
                List<Movies> movies = JsonUtils.getList(Movies[].class, t);
                MovieAdapter movieAdapter = new MovieAdapter(MoviesFragment.this.getActivity(), movies, listView);
//                Log.i("kk", "111");
                listView.setAdapter(movieAdapter);
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                if (errorNo == 401) {
                    UIHelper.toastMessage(MoviesFragment.this.getActivity(), "获取电影失败");
                } else {
                    UIHelper.toastMessage(MoviesFragment.this.getActivity(), "获取电影失败");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }



}
